<template>
  <div id="userCenterPage">
    <div style="width: 1000px; margin: 0 auto">
      <a-card
        title="个人简介"
        :hoverable="true"
        size="default"
        style="flex: 1; border-radius: 10px"
      >
        <div style="display: flex; align-items: center; gap: 16px">
          <a-avatar :size="90" :src="userMessage.userAvatar">
            <template #icon><UserOutlined /></template>
          </a-avatar>
          <div>
            <h5
              style="
                display: flex;
                justify-content: center;
                align-items: center;
                gap: 5px;
                margin-bottom: 0;
                font-size: 16px;
              "
            >
              {{ userMessage.userName }}
              <a-tag color="pink">{{
                userMessage.userRole === '' ? '未登录' : userMessage.userRole
              }}</a-tag>
            </h5>
            <p style="font-size: 14px; color: gray">账户:{{ userMessage.userAccount }}</p>
            <div style="position: absolute; top: 0; right: 0; margin: 10px">
              <a-button type="primary" ghost @click="openEditModal">编辑</a-button>
            </div>
          </div>
        </div>
      </a-card>
      <br />
      <div style="display: flex; gap: 16px">
        <!-- 左侧卡片 -->
        <a-card
          title="个人中心"
          :hoverable="true"
          size="default"
          style="width: 240px; height: 400px; border-radius: 10px"
        >
          <p><strong>用户名：</strong>{{ userMessage.userName }}</p>
          <p><strong>角色：</strong>{{ userMessage.userRole }}</p>
          <p><strong>账户：</strong>{{ userMessage.userAccount }}</p>
        </a-card>

        <!-- 右侧卡片 -->
        <a-card
          title="个人简介"
          :hoverable="true"
          size="default"
          style="flex: 1; height: 400px; border-radius: 10px"
        >
          <p style="color: gray">
            {{
              userMessage.userProfile === '' ? '这个人很懒没有留下简介~' : userMessage.userProfile
            }}
          </p>
        </a-card>
      </div>
      <div>
        <a-modal v-model:open="showEditCard" title="编辑个人信息" @ok="saveMessage">
          <a-form ref="formRef" :model="userMessage" layout="vertical" name="form_in_modal">
            <a-form-item label="头像">
              <a-upload
                name="userAvatar"
                list-type="picture-card"
                :show-upload-list="false"
                :before-upload="beforeUpload"
              >
                <a-avatar
                  :src="userMessage.userAvatar"
                  shape="square"
                  :size="80"
                  style="border: 1px dashed #d9d9d9"
                >
                  上传头像
                </a-avatar>
              </a-upload>
            </a-form-item>
            <a-form-item
              name="userName"
              label="用户名"
              :rules="[{ required: true, message: '请输入用户名!' }]"
            >
              <a-input v-model:value="userMessage.userName" />
            </a-form-item>
            <a-form-item
              name="userAccount"
              label="用户账户"
              :rules="[{ required: true, message: '请输入账户!' }]"
            >
              <a-input v-model:value="userMessage.userAccount" />
            </a-form-item>
            <a-form-item name="userProfile" label="用户简介">
              <a-textarea :rows="4" v-model:value="userMessage.userProfile" />
            </a-form-item>
          </a-form>
        </a-modal>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { userLoginStore } from '@/stores/userLoginStore'
import { updateUserUsingPost } from '@/api/user'
import { message } from 'ant-design-vue'

const showEditCard = ref(false)
const formRef = ref()
const userMessage = ref({
  id: '',
  userName: '',
  userProfile: '',
  userAvatar: '',
  userRole: '',
  userAccount: '',
})
//将已经登录的个人信息赋给userMessage,强制转化为number类型
const user = userLoginStore()
userMessage.value = user.loginUser
function openEditModal() {
  showEditCard.value = true
  console.log('触发修改信息' + showEditCard.value)
}
//头像修改
// 将文件转为 base64（也可以上传到服务器后得到URL）
const getBase64 = (file) => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => resolve(reader.result)
    reader.onerror = (error) => reject(error)
  })
}

async function beforeUpload(file) {
  const isImage = file.type.startsWith('image/')
  if (!isImage) {
    message.error('请上传图片类型的文件')
    return false
  }
  const base64 = (await getBase64(file)) as string
  userMessage.value.userAvatar = base64
  return false // 阻止自动上传
}
//保存用户信息
function saveMessage() {
  formRef.value.validate().then(() => {
    console.log('提交用户信息:', userMessage.value)
    showEditCard.value = false
    updateUserUsingPost(userMessage.value)
      .then((res) => {
        if (res.data.code == 200) {
          message.success('更新成功')
        } else {
          message.error('更新失败' + res.data.message)
        }
      })
      .catch((err) => {
        message.error('更新失败' + err.data.message)
      })
  })
}
</script>

